﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Tool
{
    class StructCovertByte
    {

        public static byte[] StructToBytes<T>(T structObj) where T : struct
        {
            // 获取结构体对象的字节数
            int size = Marshal.SizeOf(structObj);
            byte[] bytes = new byte[size];
            // 申请内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将结构体内容拷贝到上一步申请的内存空间
            Marshal.StructureToPtr(structObj, structPtr, false);
            // 将数据拷贝到byte数组
            Marshal.Copy(structPtr, bytes, 0, size);
            // 释放申请的内存
            Marshal.FreeHGlobal(structPtr);

            return bytes;
        }

        public static Packet BytesToStruct(byte[] bytes,  int nSize)
        {
            if (bytes == null)
            {
                Debug.Print("null bytes!!!!!!!!!!!!!");
            }
            IntPtr buffer = Marshal.AllocHGlobal(nSize);
            //Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize);
            try
            {
                Marshal.Copy(bytes, 0, buffer, nSize);
                return Marshal.PtrToStructure<Packet>(buffer);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                return null;
            }
            finally
            {
                Marshal.FreeHGlobal(buffer);
            }
        }
    }
}
